<?php
/**
 * 根据360SAFE整合
 */
class Safe
{
    var $getfilter = "'|(and|or)\\b.+?(>|<|=|like)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    var $postfilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    var $cookiefilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    /**
     * 获取数组对比
     * @param $array 数组
     * @param $type  比对正则库 GET库1 POST库2 COOKIE库3
     */
    public function check($array,$type=1)
    {
        foreach ($_COOKIE as $key => $value) {
            $this->StopAttack($key, $value, $cookiefilter);
        }
    }

    /**
     * 比对字符串
     * @param $StrFiltKey 指针Key
     * @param $StrFiltValue 比对的目标
     * @param $type 比对正则库 GET库1 POST库2 COOKIE库3
     */
    public function StopAttack($StrFiltKey, $StrFiltValue, $type = 1)
    {
        switch ($type) {
            case 1: //GET
                $ArrFiltReq = $this->getfilter;
                break;
            case 2: //POST
                $ArrFiltReq = $this->postfilter;
                break;
            case 3: //COOKIE
                $ArrFiltReq = $this->cookiefilter;
                break;
        }
        if (is_array($StrFiltValue)) {
            $StrFiltValue = implode($StrFiltValue);
        }
        if (preg_match("/" . $ArrFiltReq . "/is", $StrFiltValue) == 1) {
            $this->slog("<br><br>操作IP: " . $_SERVER["REMOTE_ADDR"] . "<br>操作时间: " . strftime
                ("%Y-%m-%d %H:%M:%S") . "<br>操作页面:" . $_SERVER["REQUEST_URI"] . "<br>提交方式: " . $_SERVER["REQUEST_METHOD"] .
                "<br>提交参数: " . $StrFiltKey . "<br>提交数据: " . $StrFiltValue);
            print "notice:Illegal operation!";
            exit();
        }
    }
    /**
     * 记录
     */
    function slog($logs)
    {
        $toppath = "./log/log.htm";
        $Ts = fopen($toppath, "a+");
        fputs($Ts, $logs . "\r\n");
        fclose($Ts);
    }
}
